<template>
  <BasicModal
    v-bind="$attrs"
    :showFooter="true"
    :showCancelBtn="false"
    @ok="closeModal()"
    @register="registerModal"
    width="800px"
  >
    <template #title>
      <Icon icon="ant-design:file-text-outlined" class="pr-1 m-1" />
      <span>终端日志详情</span>
    </template>
    <div v-if="record" class="log-detail">
      <a-descriptions :column="2" bordered>
        <a-descriptions-item label="设备名称">{{ record.deviceName || '-' }}</a-descriptions-item>
        <a-descriptions-item label="日志类型">
          <Tag :color="getLogTypeColor(record.logType)">
            {{ getLogTypeText(record.logType) }}
          </Tag>
        </a-descriptions-item>
        <a-descriptions-item label="日志级别">
          <Tag :color="getLogLevelColor(record.logLevel)">
            {{ getLogLevelText(record.logLevel) }}
          </Tag>
        </a-descriptions-item>
        <a-descriptions-item label="是否关键">
          <Tag :color="record.isCritical ? 'red' : 'green'">
            {{ record.isCritical ? '是' : '否' }}
          </Tag>
        </a-descriptions-item>
        <a-descriptions-item label="创建时间">{{ formatTime(record.createdTime) }}</a-descriptions-item>
        <a-descriptions-item label="发生时间">{{ formatTime(record.occurTime) }}</a-descriptions-item>
        <a-descriptions-item label="处理状态">
          <Tag :color="getProcessStatusColor(record.processStatus)">
            {{ getProcessStatusText(record.processStatus) }}
          </Tag>
        </a-descriptions-item>
        <a-descriptions-item label="SLA状态">
          <Tag :color="getSlaStatusColor(record.slaStatus)">
            {{ getSlaStatusText(record.slaStatus) }}
          </Tag>
        </a-descriptions-item>
        <a-descriptions-item label="处理人">{{ record.processor || '-' }}</a-descriptions-item>
        <a-descriptions-item label="持续时间">{{ formatDuration(record.duration) }}</a-descriptions-item>
        <a-descriptions-item label="SLA截止时间" v-if="record.slaDeadline">
          {{ formatTime(record.slaDeadline) }}
        </a-descriptions-item>
        <a-descriptions-item label="是否超时">
          <Tag :color="record.timeout ? 'red' : 'green'">
            {{ record.timeout ? '是' : '否' }}
          </Tag>
        </a-descriptions-item>
        <a-descriptions-item label="内容摘要" :span="2">
          <div class="message-content">{{ record.contentSummary || '-' }}</div>
        </a-descriptions-item>
        <a-descriptions-item label="内容详情" :span="2">
          <div class="message-content">{{ record.contentDetails || '-' }}</div>
        </a-descriptions-item>
      </a-descriptions>
    </div>
  </BasicModal>
</template>

<script lang="ts" setup name="ViewsTbTerminalLogDetail">
  import { ref, unref, computed } from 'vue';
  import { Tag, Descriptions } from 'ant-design-vue';
  import { Icon } from '/@/components/Icon';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { getTerminalLogById, TerminalLog, TerminalLogType, TerminalLogLevel } from '/@/api/tb/terminalLog';
  import dayjs from 'dayjs';

  const ADescriptions = Descriptions;
  const ADescriptionsItem = Descriptions.Item;

  const emit = defineEmits(['success', 'register']);

  const { showMessage } = useMessage();
  const record = ref<TerminalLog | null>(null);

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    try {
      setModalProps({ loading: true });
      record.value = await getTerminalLogById(data.id.id);
    } catch (error: any) {
      showMessage(`获取日志详情失败: ${error?.message || '未知错误'}`, 'error');
    } finally {
      setModalProps({ loading: false });
    }
  });

  function getLogTypeText(type: TerminalLogType): string {
    const typeMap = {
      [TerminalLogType.ALERT_LOG]: '告警日志',
      [TerminalLogType.PROCESS_LOG]: '处理日志',
      [TerminalLogType.RECEIVE_LOG]: '接收日志',
      [TerminalLogType.RECEIVE_EXCEPTION_LOG]: '接收异常',
    };
    return typeMap[type] || type;
  }

  function getLogTypeColor(type: TerminalLogType): string {
    const colorMap = {
      [TerminalLogType.ALERT_LOG]: 'red',
      [TerminalLogType.PROCESS_LOG]: 'blue',
      [TerminalLogType.RECEIVE_LOG]: 'green',
      [TerminalLogType.RECEIVE_EXCEPTION_LOG]: 'orange',
    };
    return colorMap[type] || 'default';
  }

  function getLogLevelText(level: TerminalLogLevel | string): string {
    const levelMap = {
      CRITICAL: '紧急告警',
      WARNING: '警告',
      INFO: '信息',
    };
    return levelMap[level as string] || String(level);
  }

  function getLogLevelColor(level: TerminalLogLevel | string): string {
    const colorMap = {
      CRITICAL: 'red',
      WARNING: 'orange',
      INFO: 'blue',
    };
    return colorMap[level as string] || 'default';
  }

  function formatTime(timestamp: number): string {
    return dayjs(timestamp).format('YYYY-MM-DD HH:mm:ss');
  }

  function formatDuration(ms: number): string {
    if (!ms) return '-';
    const seconds = Math.floor(ms / 1000);
    const minutes = Math.floor(seconds / 60);
    const hours = Math.floor(minutes / 60);
    const days = Math.floor(hours / 24);

    if (days > 0) return `${days}天${hours % 24}小时`;
    if (hours > 0) return `${hours}小时${minutes % 60}分钟`;
    if (minutes > 0) return `${minutes}分钟${seconds % 60}秒`;
    return `${seconds}秒`;
  }

  function getProcessStatusText(status: string): string {
    const statusMap = {
      UNPROCESSED: '未处理',
      PROCESSING: '处理中',
      PROCESSED: '已处理',
    };
    return statusMap[status] || status;
  }

  function getProcessStatusColor(status: string): string {
    const colorMap = {
      UNPROCESSED: 'orange',
      PROCESSING: 'blue',
      PROCESSED: 'green',
    };
    return colorMap[status] || 'default';
  }

  function getSlaStatusText(status: string): string {
    const statusMap = {
      NORMAL: '正常',
      WARNING: '警告',
      VIOLATED: '违反',
    };
    return statusMap[status] || status;
  }

  function getSlaStatusColor(status: string): string {
    const colorMap = {
      NORMAL: 'green',
      WARNING: 'orange',
      VIOLATED: 'red',
    };
    return colorMap[status] || 'default';
  }
</script>

<style lang="less" scoped>
  .log-detail {
    .message-content {
      word-break: break-word;
      white-space: pre-wrap;
    }

    .stack-trace {
      background-color: #fff5f5;
      padding: 12px;
      border-radius: 4px;
      font-size: 12px;
      font-family: 'Courier New', monospace;
      color: #c53030;
      max-height: 300px;
      overflow: auto;
      margin: 0;
      border: 1px solid #feb2b2;
    }

    .json-content {
      background-color: #f5f5f5;
      padding: 12px;
      border-radius: 4px;
      font-size: 12px;
      max-height: 400px;
      overflow: auto;
      margin: 0;
    }
  }
</style>
